/*
 * ProfileKeysView.java
 *
 * Created on 12 Kasım 2008 Çarşamba, 12:50
 */
package org.testis.gui.mvc.view.testdesign;

import org.testis.gui.mvc.controller.TestDesignControllerList;
import org.testis.gui.mvc.controller.testdesign.LabelSettingsController;
import org.testis.gui.mvc.view.*;
import org.testis.utils.tree.DefaultMutableLabelNode;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import org.testis.orm.classes.T_test_label;

/**
 *
 * @author  nurhat
 */
public class LabelSettingsView extends AtofBaseDialog implements
        AbstractViewPanel {

//    protected DefaultMutableLabelNode m_rootNode;
//    protected DefaultTreeModel m_treeModel;
    public LabelSettingsView(Frame owner, boolean modal) {
        super(owner, modal);
        initComponents();
    }

    public LabelSettingsView(Frame parent,
            boolean modal,
            DefaultTreeModel treeModel) {
        super(parent, modal);
        initComponents();
        labelTree.setModel(treeModel);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("/*unchecked*/")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        labelTree = new javax.swing.JTree();
        btnEdit = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Global Label Names");
        setMinimumSize(new java.awt.Dimension(320, 320));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        labelTree.setModel(new DefaultTreeModel(null));
        labelTree.setAutoscrolls(true);
        labelTree.setEditable(true);
        jScrollPane1.setViewportView(labelTree);

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnEdit)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnExit)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdd, btnDelete, btnEdit, btnExit});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDelete)
                    .addComponent(btnAdd)
                    .addComponent(btnEdit)
                    .addComponent(btnExit))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    WindowListener[] listeners = getWindowListeners();
    for (int i = 0; i <
            listeners.length; i++) {
        this.removeWindowListener(listeners[i]);
    }
    this.setVisible(false);
    this.setEnabled(false);
    TestDesignControllerList.newInstance().getLabelSettingsController().
            operationCloseWindow();
    this.dispose();
}//GEN-LAST:event_formWindowClosed

private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
    this.dispose();
}//GEN-LAST:event_btnExitActionPerformed

private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
    DefaultMutableLabelNode selectedNode = getSelectedNode();
    boolean confirmed = confirmDeleteDialog(selectedNode);
    if (confirmed) {
        // remove selected label
        removeLabel(selectedNode);
    }
}//GEN-LAST:event_btnDeleteActionPerformed

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
    String labelName = JOptionPane.showInputDialog("Enter Label Name:");
    if (labelName != null && !labelName.trim().equals("")) {
        boolean labelNameExists = TestDesignControllerList.newInstance().getLabelSettingsController().operationCheckLabelNameExists(labelName);
        if (!labelNameExists) {
            DefaultMutableLabelNode selectedNode = getSelectedNode();
            addLabel(selectedNode, labelName);
        } else {
            JOptionPane.showMessageDialog(this, "Label name: '" + labelName + "' already defined",
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}//GEN-LAST:event_btnAddActionPerformed

private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
    DefaultMutableLabelNode selectedNode = getSelectedNode();
    if (selectedNode != null && selectedNode.getLabel() != null) {
        T_test_label label = selectedNode.getLabel();
        String labelName = JOptionPane.showInputDialog("Enter Label Name:", label.getName());
        if (labelName != null && !labelName.trim().equals("")) {
            saveLabel(label.getId(), labelName);
        }
    }


}//GEN-LAST:event_btnEditActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnExit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree labelTree;
    // End of variables declaration//GEN-END:variables

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                LabelSettingsController.SHOW_VIEW)) {
            TestDesignControllerList.newInstance().getLabelSettingsController().operationLoadLabels();
            this.centerParent();
        } else if (evt.getPropertyName().equals(
                LabelSettingsController.SHOW_ERROR)) {
            String val = (String) evt.getNewValue();
            JOptionPane.showMessageDialog(
                    this,
                    val,
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        } else if (evt.getPropertyName().equals(
                LabelSettingsController.PARAMETER_MODEL_CHANGED)) {
            labelTree.setModel((DefaultTreeModel) evt.getNewValue());
            labelTree.updateUI();
            expandTree();
//            labelTableModel.getModel().addTableModelListener(addListener());
        }
    }

    /*
    // Remove the currently selected node.
    private void removeCurrentNode() {
    DefaultMutableLabelNode currentNode = getSelectedNode();
    if (currentNode != null) {
    MutableTreeNode parent = (MutableTreeNode) (currentNode.getParent());
    if (parent != null) {
    T_test_label label = currentNode.getLabel();
    if (label != null) {
    TestDesignControllerList.newInstance().getLabelSettingsController().
    operationRemoveLabel(label.getId());
    }
    m_treeModel.removeNodeFromParent(currentNode);
    }
    }
    }
     */
    private DefaultMutableLabelNode getSelectedNode() {
        DefaultMutableLabelNode currentNode = null;
        TreePath currentSelection = labelTree.getSelectionPath();
        if (currentSelection != null) {
            currentNode = (DefaultMutableLabelNode) (currentSelection.getLastPathComponent());
        }
        return currentNode;
    }

    /*
    // Add child to the currently selected node.
    private DefaultMutableLabelNode addObject(Object child) {
    DefaultMutableLabelNode parentNode = m_rootNode;
    TreePath parentPath = labelTree.getSelectionPath();
    if (parentPath != null) {
    parentNode = (DefaultMutableLabelNode) (parentPath.getLastPathComponent());
    }
    return addObject(parentNode, child, true);
    }

    private DefaultMutableLabelNode addObject(DefaultMutableLabelNode parent,
    Object child) {
    return addObject(parent, child, false);
    }
     */

    /*
    private DefaultMutableLabelNode addObject(DefaultMutableLabelNode parent,
    Object child,
    boolean shouldBeVisible) {
    DefaultMutableLabelNode childNode = new DefaultMutableLabelNode(new LabelTreeNode(child.toString()));
    if (parent == null) {
    parent = m_rootNode;
    }
    //It is key to invoke this on the TreeModel, and NOT DefaultMutableTreeNode
    m_treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
    //Make sure the user can see the lovely new node.
    if (shouldBeVisible) {
    labelTree.scrollPathToVisible(new TreePath(childNode.getPath()));
    }
    return childNode;
    }
     */

    /*
    private void addLabel(int containerLabelId, String labelName) {
    TestDesignControllerList.newInstance().getLabelSettingsController().
    operationAddLabel(labelName, containerLabelId);
    }
     */
    private void addLabel(DefaultMutableLabelNode selectedNode, String name) {
        T_test_label containerLabel = null;
        if (selectedNode != null) {
            containerLabel = selectedNode.getLabel();
        }
        int containerId = 0;
        if (containerLabel != null) {
            containerId = containerLabel.getId();
        }
        TestDesignControllerList.newInstance().getLabelSettingsController().
                operationAddLabel(name, containerId);
    }

    private void saveLabel(int id, String name) {
        TestDesignControllerList.newInstance().getLabelSettingsController().
                operationEditLabel(id, name);
    }

    private void removeLabel(DefaultMutableLabelNode selectedNode) {
        if (selectedNode == null) {
            return;
        }
        T_test_label label = selectedNode.getLabel();
        if (label != null) {
            TestDesignControllerList.newInstance().getLabelSettingsController().
                    operationRemoveLabel(label.getId());
        }
    }

    private void removeSelectedLabel() {
        DefaultMutableLabelNode selectedNode = getSelectedNode();
        removeLabel(selectedNode);
    }

    private boolean confirmDeleteDialog(DefaultMutableLabelNode selectedNode) {
        if (selectedNode == null) {
            return false;
        }
        T_test_label label = selectedNode.getLabel();
        if (label == null) {
            return false;
        }
        boolean confirmForDelete = false;
        int result = javax.swing.JOptionPane.showConfirmDialog(null,
                "Are you sure you want to delete this label?",
                "Delete Confirmation",
                javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                javax.swing.JOptionPane.QUESTION_MESSAGE);
        if (result == javax.swing.JOptionPane.YES_OPTION) {
            confirmForDelete = true;
            if (TestDesignControllerList.newInstance().getLabelSettingsController().
                    operationCheckIsInUse(label.getId())) {
                result = javax.swing.JOptionPane.showConfirmDialog(null,
                        "This label is in use! Are you sure you want to delete this label?",
                        "Delete Confirmation",
                        javax.swing.JOptionPane.YES_NO_CANCEL_OPTION,
                        javax.swing.JOptionPane.QUESTION_MESSAGE);
                if (result == javax.swing.JOptionPane.YES_OPTION) {
                    confirmForDelete = true;
                } else {
                    confirmForDelete = false;
                }
            }
        }
        return confirmForDelete;
    }

    private void expandTree() {
//        labelTree.expandPath(labelTree.getPathForRow(0));
        for (int i = 0; i < labelTree.getRowCount(); i++) {
            labelTree.expandRow(i);
        }
//        tree.collapsePath(tree.getPathForRow(0));
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TestDesignControllerList.newInstance().getLabelSettingsController().startLoader();
            }
        });
    }
}
//
//private class LabelTreeNodeEditor{
//}

